package com.sayice.robotconflict.game.handler;

import com.sayice.robotconflict.common.util.SpringContextUtil;
import com.sayice.robotconflict.entity.FriendReqEntity;
import com.sayice.robotconflict.entity.SocialPlayerEntity;
import com.sayice.robotconflict.game.msg.Message;
import com.sayice.robotconflict.game.msg.data.send.FriendInfo;
import com.sayice.robotconflict.game.object.Player;
import com.sayice.robotconflict.service.SocialService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 社交信息消息处理器
 *
 * @author shubing
 */
@Slf4j
public class SocialHandler extends ChannelInboundHandlerAdapter {
    private static final SocialService SOCIAL_SERVICE = SpringContextUtil.getBean(SocialService.class);
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Object[] playerAndMsg = (Object[]) msg;
        Player player = (Player) playerAndMsg[0];
        Message message = (Message) playerAndMsg[1];
        if ("social".equals(message.getType())) {
            switch (message.getAction()) {
                // 获取好友列表
                case "getFriends": {
                    ctx.channel().writeAndFlush(new Message("social", "friends", getFriends(player.id)).toJson());
                    break;
                }
                // 根据玩家名查找可添加为好友的玩家
                case "findPlayers": {
                    String name = (String) message.getData();
                    // 查询结果过滤掉已经是好友的
                    List<SocialPlayerEntity> friends = SOCIAL_SERVICE.queryFriends(player.id);
                    List<SocialPlayerEntity> socialPlayerEntities = SOCIAL_SERVICE.queryPlayersByNameExcept(name, player.id)
                            .stream().filter(it -> friends.stream().noneMatch(f -> f.getId().equals(it.getId())))
                            .collect(Collectors.toList());
                    List<FriendInfo> friendInfos = FriendInfo.listOf(socialPlayerEntities);
                    ctx.channel().writeAndFlush(new Message("social", "players", friendInfos).toJson());
                    break;
                }
                // 获取好友申请
                case "getFriendReqs": {
                    List<FriendReqEntity> friendReqEntities = SOCIAL_SERVICE.queryFriendReqs(player.id);
                    ctx.channel().writeAndFlush(new Message("social", "friendReqs", friendReqEntities).toJson());
                    break;
                }
                // 发送好友申请
                case "sendFriendReq": {
                    String targetId = (String) message.getData();
                    SOCIAL_SERVICE.addFriendReq(targetId, player.id);
                    break;
                }
                // 阅读好友申请
                case "readFriendReq": {
                    String fromId = (String) message.getData();
                    SOCIAL_SERVICE.readFriendReq(player.id, fromId);
                    // 发送新数据给客户端
                    List<FriendReqEntity> friendReqEntities = SOCIAL_SERVICE.queryFriendReqs(player.id);
                    ctx.channel().writeAndFlush(new Message("social", "friendReqs", friendReqEntities).toJson());
                    break;
                }
                // 同意好友申请
                case "agreeFriendReq": {
                    String fromId = (String) message.getData();
                    if (SOCIAL_SERVICE.existsFriendReq(player.id, fromId)) {
                        SOCIAL_SERVICE.addFriend(player.id, fromId);
                    }
                    SOCIAL_SERVICE.deleteFriendReq(player.id, fromId);
                    // 发送新数据给客户端
                    ctx.channel().writeAndFlush(new Message("social", "friends", getFriends(player.id)).toJson());
                    List<FriendReqEntity> friendReqEntities = SOCIAL_SERVICE.queryFriendReqs(player.id);
                    ctx.channel().writeAndFlush(new Message("social", "friendReqs", friendReqEntities).toJson());
                    break;
                }
                // 忽略好友申请
                case "ignoreFriendReq": {
                    String fromId = (String) message.getData();
                    SOCIAL_SERVICE.deleteFriendReq(player.id, fromId);
                    // 发送新数据给客户端
                    List<FriendReqEntity> friendReqEntities = SOCIAL_SERVICE.queryFriendReqs(player.id);
                    ctx.channel().writeAndFlush(new Message("social", "friendReqs", friendReqEntities).toJson());
                    break;
                }
                // 删除好友
                case "deleteFriend": {
                    String targetId = (String) message.getData();
                    SOCIAL_SERVICE.deleteFriend(player.id, targetId);
                    // 发送新数据给客户端
                    ctx.channel().writeAndFlush(new Message("social", "friends", getFriends(player.id)).toJson());
                    break;
                }
                default:
                    break;
            }
        } else {
            ctx.fireChannelRead(playerAndMsg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("NettyHandler Exception from " + ctx.channel().remoteAddress(), cause);
        ctx.channel().close();
    }
    
    /**
     * 获取好友信息
     *
     * @param playerId 玩家ID
     */
    private List<FriendInfo> getFriends(String playerId) {
        List<SocialPlayerEntity> socialPlayerEntities = SOCIAL_SERVICE.queryFriends(playerId);
        return FriendInfo.listOf(socialPlayerEntities);
    }
}
